#!/usr/bin/python2
# -*- coding: utf-8 -*-

import re
try:
    from lib.mol import Mol2pic
except:
    import sys
    sys.path.append('..')
    from mol import Mol2pic

reg = re.compile(r'J[a-z]')

def Gen_confirm_query(info_dic):
    query = {}

    if not (info_dic.has_key('id') and info_dic.has_key('mol')):
        return {}
    mol = info_dic['mol']
    if 'Ja' in info_dic['mol']:
        if not info_dic.has_key('ms_obj'):
            return {}

        smi = Mol2pic(reg.sub('H ',
            unicode(mol.replace('\r', '').replace('\n', '\\n')))).to_smi()
        term = ''
        ms_obj = info_dic['ms_obj']
        mw = float(ms_obj.precursor) - float(ms_obj.adduct)
        iso_width = float(ms_obj.iso_width)
        deviation = float(ms_obj.deviation)
        query['mol'] = smi
        if ms_obj.resolution == 0:
            term += '%s:%s[EXMASS]' %(mw - iso_width, mw + iso_width)
        elif ms_obj.resolution == 1:
            term += '%s:%s[EXMASS]' %(mw*(1 - deviation), mw*(1 + deviation))

        if info_dic.has_key('charge'):
            query['term'] = '%s AND %s[CHG]' %(term, info_dic['charge'])

    else:
        smi = Mol2pic(unicode(mol.replace('\r', '').replace('\n', '\\n'))).to_smi()
        query['isotope'] = 4
        query['mol'] = smi
        query['query'] = smi

    query['id'] = info_dic['id']
    query['num_results'] = info_dic.setdefault('num_results', 10)

    return query
